<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户名字" prop="khname">
        <el-input
          v-model="queryParams.khname"
          placeholder="请输入客户名字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="型号" prop="xhgg">
        <el-input
          v-model="queryParams.xhgg"
          placeholder="请输入型号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="制造厂商" prop="zzcs">
        <el-input
          v-model="queryParams.zzcs"
          placeholder="请输入制造厂商"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出厂编号" prop="ccbh">
        <el-input
          v-model="queryParams.ccbh"
          placeholder="请输入出厂编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="管理编号" prop="glbh">
        <el-input
          v-model="queryParams.glbh"
          placeholder="请输入管理编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单价" prop="dj">
        <el-input
          v-model="queryParams.dj"
          placeholder="请输入单价"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-row style="margin-bottom: 15px">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['gd:khbjk:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['gd:khbjk:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['gd:khbjk:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['gd:khbjk:export']"
        >全部导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="khbjkList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客户名字" align="center" prop="khname" />
      <el-table-column label="序号" align="center" prop="xh" />
      <el-table-column label="设备名称" align="center" prop="name" />
      <el-table-column label="型号" align="center" prop="xhgg" />
      <el-table-column label="制造厂商" align="center" prop="zzcs" />
      <el-table-column label="出厂编号" align="center" prop="ccbh" />
      <el-table-column label="管理编号" align="center" prop="glbh" />
      <el-table-column label="数量" align="center" prop="number" />
      <el-table-column label="单价" align="center" prop="dj" />
      <el-table-column label="小计" align="center" prop="zj" />
      <el-table-column label="服务方式" align="center" prop="fwfs" />
      <el-table-column label="备注" align="center" prop="bz" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="userName === 'admin'">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['gd:khbjk:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['gd:khbjk:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改客户报价库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="客户名字" prop="khname">
              <el-input v-model="form.khname" placeholder="请输入客户">
                <el-button type="primary" slot="prepend" @click.native="selectUser"> <i class="el-icon-user-solid"></i> </el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="导入类型" prop="drlx">
              <el-checkbox-group v-model="drlx" @change="selectDrlx">
                <el-checkbox v-for="item in drlxList" :label="item.dictValue">{{item.dictLabel}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件" prop="fjid">
              <el-upload
                class="upload-demo"
                :action="src"
                name="files"
                :on-success="handleSuccess"
                :on-error="handleError"
                :before-remove="handleRemove"
                :headers="uploadHeaders"
                accept=".xlsx, .xls"
                multiple
                :file-list="fjList"
                :on-preview="handlePreview"
              >
                <el-button size="small" type="primary"> <i class="el-icon-upload"></i> 点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传Excel文件</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="bz">
              <el-input v-model="form.bz" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">导 入</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <khList v-if="showUser" :showUser="showUser" @selectData="selectData" @closeDialog="closeDialog"></khList>
  </div>
</template>

<script>
import { listKhbjk, getKhbjk, delKhbjk, addKhbjk, updateKhbjk, importData } from "@/api/gd/khbjk";
import khList from "@/views/gd/ywd/khList.vue";
import { getToken } from '@/utils/auth'
import { updateLswgd } from '@/api/gd/lswgd'
import { delFj } from '@/api/gd/fj'
import { updateYwd } from '@/api/gd/ywd'
import axios from 'axios'
export default {
  name: "Khbjk",
  components: { khList },
  data() {
    return {
      drlx: ['yqmc','yqxh','ccbh','glbh'],
      drlxList: [],
      // 附件上传 开始
      src: this.uploadSrc + '/gd/fj/file/batchUpload',
      uploadHeaders: { 'Authorization': 'Bearer ' + getToken() }, // 如果需要CSRF保护的话
      fjList: [],
      // 附件上传 结束
      showUser: false,
      userName: this.$store.getters.name,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户报价库表格数据
      khbjkList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        xh: undefined,
        name: undefined,
        xhgg: undefined,
        zzcs: undefined,
        ccbh: undefined,
        glbh: undefined,
        number: undefined,
        dj: undefined,
        zj: undefined,
        fwfs: undefined,
        bz: undefined,
        kkid: undefined,
        khname: undefined,
        khdz: undefined,
        khlxr: undefined,
        khdh: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        drlx: [
          { required: true, message: "报导入类型不能为空", trigger: "blur" }
        ],
        khname: [
          { required: true, message: "客户名字不能为空", trigger: "blur" }
        ],
        fj: [
          { required: true, message: "客户名字不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDict();
  },
  methods: {
    getDict() {
      // 导入类型
      this.getDicts("gd_drlx").then(res => {
        this.drlxList = res.data
      })
    },
    selectDrlx(val) {
      this.form.drlx = val.toString()
    },
    // ======  上传开始  ======
    handleSuccess(response, file, fileList) {
      if (response !== null && response !== undefined) {
        // 获取当前的上传的附件id
        let fileIds = []
        fileList.forEach(item => {
          if (item.response !== undefined) {
            fileIds.push(item.response[0].fj)
          }
        })
        // 更新状态或者通知用户上传成功
        this.$message.success('上传成功');
        // 上传成功以后，将id设置
        this.form.fjid = fileIds.toString()
      }
    },
    // 上传失败回调
    handleError(err, file) {
      // 处理错误并通知用户
      this.$message.error('上传失败：', err);
      this.fjList = []
    },
    // 删除回调
    handleRemove(file, fileList) {
      // 调用删除附件功能，将附件进行删除
      let fjId = []
      let id = file.id || file.response[0].fj
      fjId.push(id)
      delFj(fjId).then(res => {
        if (res.code === 200) {
          this.$message.success("删除成功！")
        }
      })
    },
    // 文件点击回调
    async handlePreview(file) {
      let id = file.id || file.response[0].fj
      const response = await axios.get(this.uploadSrc + `/gd/fj/download/` + id, { responseType: 'blob', headers: this.uploadHeaders });
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url
      link.download = file.name;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },

    // ======  上传结束  ====
    closeDialog() {
      this.showUser = false
    },
    selectUser() {
      this.showUser = true
    },
    selectData(row) {
      this.form.khid = row.id
      this.form.khbh = row.bh
      this.form.khname = row.khname
      this.closeDialog()
    },
    /** 查询客户报价库列表 */
    getList() {
      this.loading = true;
      listKhbjk(this.queryParams).then(response => {
        this.khbjkList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.fjList = []
      this.$set(this, "drlx" ,['yqmc','yqxh','ccbh','glbh'])
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        xh: undefined,
        name: undefined,
        xhgg: undefined,
        zzcs: undefined,
        ccbh: undefined,
        glbh: undefined,
        number: undefined,
        dj: undefined,
        zj: undefined,
        fwfs: undefined,
        bz: undefined,
        kkid: undefined,
        khname: undefined,
        khdz: undefined,
        khlxr: undefined,
        khdh: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.$set(this.form, 'drlx', this.drlx.toString())
      this.open = true;
      this.title = "导入客户报价库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getKhbjk(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改客户报价库";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          importData(this.form).then(response => {
            this.$modal.msgSuccess("导入成功！");
            this.open = false;
            this.getList();
          }).finally(() => {
            this.buttonLoading = false;
          });

          // if (this.form.id != null) {
          //   updateKhbjk(this.form).then(response => {
          //     this.$modal.msgSuccess("修改成功");
          //     this.open = false;
          //     this.getList();
          //   }).finally(() => {
          //     this.buttonLoading = false;
          //   });
          // } else {
          //   addKhbjk(this.form).then(response => {
          //     this.$modal.msgSuccess("新增成功");
          //     this.open = false;
          //     this.getList();
          //   }).finally(() => {
          //     this.buttonLoading = false;
          //   });
          // }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除客户报价库编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delKhbjk(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('gd/khbjk/export', {
        ...this.queryParams
      }, `khbjk_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
